package com.zp.security.oauth2.exception;

import com.zp.common.base.constant.ResultCode;
import com.zp.common.base.resp.BaseResp;
import com.zp.common.base.utils.ResponseUtils;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * oauth2.0认证失败处理器
 *
 * @author zp
 */
@Component
public class OAuthServerAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        if (exception instanceof BadCredentialsException) {
            ResponseUtils.result(response,new BaseResp<>(ResultCode.CLIENT_AUTHENTICATION_FAILED));
        }
        ResponseUtils.result(response,new BaseResp<>(ResultCode.UNAUTHORIZED));
    }
}
